package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.exception.LogicException;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] ids) {
        //加密密码，使用用户名作为盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toHex());


        employeeMapper.insert(employee);
        insertRelation(employee, ids);
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        employeeMapper.delete(employee.getId());
        insertRelation(employee, ids);
    }

    private void insertRelation(Employee employee, Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (long roleId : ids) {
                //往中间表中插入关系数据
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee selectOne(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public List<Employee> queryForData(QueryObject qo) {
        return employeeMapper.queryForData(qo);
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForData(qo);
        return new PageInfo<>(employees);

        /*int count = employeeMapper.queryForCount(qo);

        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,
                count == 0 ?
                Collections.emptyList() : employeeMapper.queryForData(qo));*/
    }

    /*@Override
    public int queryForCount(QueryObject qo) {
        int totalCount = employeeMapper.queryForCount(qo);
        return totalCount;
    }*/

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)) {
            throw new LogicException("用户名不能为空");
        }

        Employee employee = employeeMapper.login(username);
        if (employee == null) {
            throw new RuntimeException("账号错误");
        } else if (!employee.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }
        //登录成功
        return employee;
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        //创建一个工作簿
        HSSFWorkbook wk = new HSSFWorkbook();
        //创建工作表
        HSSFSheet sheet = wk.createSheet("员工通讯录");
        List<Employee> employees = employeeMapper.selectAll();
        //每个员工一行数据
        //创建行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            row = sheet.createRow(i + 1);
            //创建单元格
            row.createCell(0).setCellValue(StringUtils.hasText(employee.getName()) ? employee.getName() : "null");
            row.createCell(1).setCellValue(StringUtils.hasText(employee.getEmail()) ? employee.getEmail() : "null");
            if (employee.getAge() != null) {
                row.createCell(2).setCellValue(employee.getAge());
            }
        }

        //输出内容到响应流
        return wk;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //使用poi读取上传过来的文件
        Workbook wk = new HSSFWorkbook(file.getInputStream());
        Employee employee = new Employee();
        //拿到文件
        Sheet sheet = wk.getSheetAt(0);
        //获取最后一行的行数
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            employee.setName(name);
            String email = row.getCell(1).getStringCellValue();
            employee.setEmail(email);
            Cell cell = row.getCell(2);

            if (cell.getCellType() == CellType.NUMERIC) {
                double age = cell.getNumericCellValue();
                employee.setAge((int) age);
            } else {
                String age = cell.getStringCellValue();
                employee.setAge(Integer.valueOf(age));
            }
            //Employee employee = new Employee(name, email, Integer.valueOf(age));
            employeeMapper.insert(employee);
        }
        //读行
//        sheet.
    }

    @Override
    public List<Employee> selectByPassword(String srcPassword) {
        return employeeMapper.selectByPassword(srcPassword);
    }

    @Override
    public void updatePw(Long id, String newPassword) {
        employeeMapper.updatePw(id, newPassword);
    }

    @Override
    public void changeStatus(Long id) {
        employeeMapper.changeStatus(id);
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
